/**
 * 
 */
package com.vivid.dynamics.oknow.dao.impl;

import java.io.Serializable;
import java.util.List;

import org.apache.log4j.Logger;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.vivid.dynamics.oknow.dao.IGroupDAO;
import com.vivid.dynamics.oknow.model.Group;

/**
 *
 * @author jason
 * created at:: Jul 28, 2011 12:21:01 PM
 */
public class GroupDAOImpl implements IGroupDAO {

	static Logger logger=Logger.getLogger(GroupDAOImpl.class);
	
	/* ********************* */
	/* *    HQL entries    * */
	/* ********************* */
	
	/**
	 * query all Groups (no criteria)
	 * order by "id" DESC
	 */
	static final String HQL_SELECT_ALL="from Group groupAlias order by groupAlias.id desc";
	
	@Autowired
	private SessionFactory sessionFactory;
	
	/**
	 * {@inheritDoc}<p/>
	 * <b>PS</b>. use 'get' instead of 'load'; get will not throw
	 * Exception when there is no entity bounded to the give 'id'
	 * @see com.vivid.dynamics.oknow.dao.IGroupDAO#getGroupByKey(int)
	 */
	@Override
	@Transactional(readOnly = true, propagation=Propagation.REQUIRED)
	public Group getGroupByKey(int pId) {
		Session aSession=this.sessionFactory.getCurrentSession();
		Group aGrp=null;
		
		aGrp=(Group) aSession.get(Group.class, Integer.valueOf(pId));

		return aGrp;
	}
	
	/**
	 * {@inheritDoc}
	 */
	@Override
	@Transactional(propagation=Propagation.REQUIRED)
	public Serializable newGroup(Group pGroup) {
		Serializable aKey=null;
		Session aSession=this.sessionFactory.getCurrentSession();
		
		if (pGroup!=null) {
			aKey=aSession.save(pGroup);
			if (logger.isDebugEnabled()) {
				logger.debug("[newGroup] key is :: "+aKey);
			}
		}
		return aKey;
	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	@Transactional(propagation=Propagation.REQUIRED)
	public void updateGroup(Group pGroup) {
		Session aSession=this.sessionFactory.getCurrentSession();
		if (pGroup!=null) {
			aSession.update(pGroup);
		}
	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	@Transactional(propagation=Propagation.REQUIRED)
	public void deleteGroup(Group pGroup) {
		Session aSession=this.sessionFactory.getCurrentSession();
		if (pGroup!=null) {
			aSession.delete(pGroup);
		}
	}

	/**
	 * {@inheritDoc}
	 */
	@SuppressWarnings("unchecked")
	@Override
	@Transactional(readOnly=true, propagation=Propagation.REQUIRED)
	public List<Group> getAll() {
		Session aSession=this.sessionFactory.getCurrentSession();
		List<Group> aList=null;
		
		aList=aSession.createQuery(HQL_SELECT_ALL).list();
		
		return aList;
	}

}
